package com.example.security.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.security.bean.User;
import com.example.security.event.RegisterEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class ActiveController {

  private final ApplicationEventPublisher publisher;

  private final RedisTemplate<String, Object> redisTemplate;

  public ActiveController(
      ApplicationEventPublisher publisher, RedisTemplate<String, Object> redisTemplate) {
    this.publisher = publisher;
    this.redisTemplate = redisTemplate;
  }

  @GetMapping("/active/{token}")
  public ResponseEntity<?> active(@PathVariable String token) {

    // jwt token
    try {
      var decodedToken =
          JWT.require(Algorithm.HMAC512("ACTIVE-KEY".getBytes())).build().verify(token);
      var userId = decodedToken.getClaim("id").asInt();
      log.info("用户 " + userId.toString() + " token合法, 准备激活");
      return ResponseEntity.ok("激活成功");
    } catch (TokenExpiredException e) {
      log.info("用户token过期");
      // 发送一个用户激活的事件
      User user = new User();
      // 从token里面获取用户的邮件, 用户名, id
      JWT.decode(token).getClaim("email");
      RegisterEvent event = new RegisterEvent(this, user);
      publisher.publishEvent(event);
      return ResponseEntity.ok("再次发送了确认邮件");
      // 再次发送邮件
    } catch (Exception e) {
      log.info("用户token不合法");
      return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("激活非法");
    }
  }

  @GetMapping("/active/redis/{token}")
  public ResponseEntity<?> activeRedis(@PathVariable String token) {
    var ops = redisTemplate.boundValueOps("token");
    var userId = ops.get();
    if (userId == null) {
      log.info("用户token不合法");
      // 继续发送一下, 此处有问题, Redis过期后根据这个token找不到用户信息
      return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("激活非法");
    } else {
      log.info("用户 " + userId.toString() + " token合法, 准备激活");
      // 修改这个用户的activated字段
      return ResponseEntity.ok("激活成功");
    }
  }
}
